<template>
  <div>
    <div class="mt-2 text-gray-500">
      智能重合闸:
      <div style="float: right">
        {{ ip }}
        <span class="ml-1 text-base mr-2">-{{ device.netSignal }}dBn</span>
      </div>
    </div>
    <el-row
      v-for="(leakageSwitch,index) in leakageSwitchList"
      :key="index"
      class="mt-2"
      :gutter="5"
    >
      <el-col :span="9">
        <el-card style="height: 140px;">
          <div style="display: flex;justify-content: space-between">
            <div style="text-align: center;flex-grow: 1">
              <div>
                <i
                  style="font-size: 40px;margin-top: 20px"
                  :class="['fa', rtu.acV.value > 50 ? 'fa-plug text-green-400':'fa-chain-broken0 text-red-400']"
                  @click="explainClick(rtu.acV)"
                />
              </div>
              <span v-if="rtu.acV.value > 50" class="text-xs">市电连接</span>
              <span v-else class="text-xs">市电断开</span>
            </div>
            <div style="flex-basis: 160px">
              <div v-for="(explain ,explainIndex) in leakageSwitch.explainList" :key="explainIndex" class="mx-1 flex">
                <div v-if="explain.keyName === 'recloseStu'">
                  <!--                  <el-switch-->
                  <!--                    :value="explain.rawValue"-->
                  <!--                    active-value="1"-->
                  <!--                    inactive-value="0"-->
                  <!--                  />-->
                  <i
                    class="fa fa-power-off text-xl"
                    :class="explain.rawValue == 1 ? 'text-green-400' : 'text-red-400'"
                  />
                  <div class="text-xs mt-2">
                    <span v-if="explain.rawValue == 1">开启</span>
                    <span v-else>关闭</span>
                  </div>
                </div>
                <div v-else-if="explain.keyName === 'lastFaultType'" class="text-xs">
                  故障类型:{{ explain.value }}
                </div>
                <!--                <div v-else-if="explain.keyName === 'lastFaultData'" class="text-xs">-->
                <!--                  故障值:{{ explain.value }}-->
                <!--                </div>-->
              </div>
              <div/>
              <div class="mt-2">
                <div v-for="(setting ,settingIndex) in leakageSwitch.settingList" :key="settingIndex" class="mx-1 flex">
                  <div v-if="setting.keyName === 'setReClose' || setting.keyName === 'setAirSw'">
                    <div class="flex content-center">
                      <div
                        v-for="(param,index2) in setting.paramList"
                        :key="index2"
                        class="rounded-md text-xs"
                        style="background-color:#03c2c2;color: white;text-align: center;padding: 6px 10px;margin: 2px"
                        @click="leakageSwitchChange(setting,param.value)"
                      >{{ param.name }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="15">
        <el-card
          style="height: 140px"
        >
          <div style="width: 100%">
            <el-row :gutter="10" class="flex-grow mt-2">
              <el-col
                v-for="(explain ,explainIndex) in leakageSwitch.explainList"
                v-if="explain.keyName ==='AC_I' || explain.keyName ==='AC_V' || explain.keyName ==='LeakI' "
                :key="explainIndex"
                :span="8"
                style="text-align: center"
              >
                <div class="mt-3" @click="explainClick(explain)">
                  <div v-if="explain.keyName ==='AC_I' || explain.keyName ==='AC_V' || explain.keyName ==='LeakI'">
                    <div class="text-sm">{{ explain.name }} <i
                      :class="explain.warnNum > 0 ? 'el-icon-warning':'el-icon-warning-outline'"
                    /></div>
                    <div
                      class="text-gray-400 text-3xl mt-3 leading-8 h-8"
                      style="color: #03c2c2;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;font-weight: lighter;text-align: center"
                    >
                      {{ explain.value }}
                      <span class="text-xl mt-2">{{ explain.unit }}</span>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div>
      <div class="mt-2 text-gray-500">
        {{ $t('power') }}:
      </div>
      <el-row :gutter="5">
        <el-col v-for="(power,index) in powerList" :key="index" :span="8">
          <el-card class="my-2">
            <i class="el-icon-switch-button" :style="{color:power.enable === '1'? '#F00' : '#000'}"/>
            <i v-if="parseFloat(power.i) > 0.02" class="el-icon-connection"/>
            <el-switch
              v-model="power.enable"
              style="float: right"
              active-value="1"
              inactive-value="0"
              @change="powerSwitch(power)"
            />
            <div class="mt-5 flex justify-between">
              <div>
                <div>电源{{ index + 1 }}</div>
                <div class="text-gray-400 text-xs">12V {{ power.i }}A</div>
              </div>
              <div v-if="index === 0" style="float: right" class="text-xs text-gray-500 leading-6">
                <span
                  :class="power.mode !== '1' ? 'text-black':'text-gray-300'"
                  @click="switch1ModelChange('1')"
                >自动</span>
                <span>/</span>
                <span
                  :class="power.mode !== '0' ? 'text-black':'text-gray-300'"
                  @click="switch1ModelChange('0')"
                >手动</span>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="my-2 text-gray-500">
      <span>输入检测</span>
    </div>
    <el-row :gutter="5">
      <el-col :span="6">
        <el-card>
          <i :class="input1.rawValue === '1' ? 'el-icon-lock' : 'el-icon-unlock text-red-500'"/>
          <div class="mt-5 flex justify-between">
            <div>
              <div>箱门</div>
              <div class="text-gray-400 text-xs">
                <span v-if="input1.rawValue === '1'">箱门关</span>
                <span v-else>箱门开</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <i :class="input2.rawValue === '1' ? 'el-icon-lightning text-red-500' : 'el-icon-cloudy'"/>
          <div class="mt-5 flex justify-between">
            <div>
              <div v-if="input2.rawValue === '1'">防雷失效</div>
              <div v-else>防雷正常</div>
              <div class="text-gray-400 text-xs">雷击次数:{{ lightningStrikes }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <i :class="input3.rawValue === '1' ? 'el-icon-s-help text-red-500' : 'el-icon-help'"/>
          <div class="mt-5 flex justify-between">
            <div>
              <div>{{ input3.remark }}</div>
              <div class="text-gray-400 text-xs">
                <span v-if="input3.value !=0 && input3.value !=1">{{ input3.value }}</span>
                <span v-else-if="input3.rawValue === '1'">高电平</span>
                <span v-else>低电平</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <i :class="input4.rawValue === '1' ? 'el-icon-s-help text-red-500' : 'el-icon-help'"/>
          <div class="mt-5 flex justify-between">
            <div>
              <div>{{ input4.remark }}</div>
              <div class="text-gray-400 text-xs">
                <span v-if="input4.value !=0 && input4.value !=1">{{ input4.value }}</span>
                <span v-else-if="input4.rawValue === '1'">高电平</span>
                <span v-else>低电平</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <div class="mt-2 text-gray-500">
      环境:
    </div>
    <el-row :gutter="5">
      <el-col :span="6">
        <el-card v-if="eFlooding" class="my-2">
          <i class="fa fa-bath" aria-hidden="true"/>
          <span style="float: right">{{ eFlooding.value === '1' ? '水浸' : '正常' }}</span>
          <div class="mt-5">
            <div>{{ $t('waterImmersion') }}</div>
            <div class="text-gray-400 text-xs">{{ formatDate(eFlooding.valueDate) }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card v-if="eHum" class="my-2">
          <i class="fa fa-tint" aria-hidden="true"/>
          <span style="float: right">{{ eHum.value }}%RH</span>
          <div class="mt-5">
            <div>{{ $t('humidity') }}</div>
            <div class="text-gray-400 text-xs">{{ formatDate(eHum.valueDate) }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card v-if="eTemp" class="my-2">
          <i class="fa fa-thermometer-empty" aria-hidden="true"/>
          <span style="float: right">{{ eTemp.value }}°C</span>
          <div class="mt-5">
            <div>{{ $t('temperature') }}</div>
            <div class="text-gray-400 text-xs">{{ formatDate(eTemp.valueDate) }}</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="my-2">
          <i class="fa fa-snowflake-o" aria-hidden="true"/>
          <el-switch
            v-model="fan.enable"
            style="float: right"
            active-value="1"
            inactive-value="0"
            :disabled="fan.model === '1'"
            @change="fanSwitch"
          />

          <div class="mt-5">{{ $t('fan') }}</div>
          <div class="text-gray-400 text-xs" @click.stop="fanSetVisible = true">
            <span :class="fan.model !== '1' ? 'text-black':'text-gray-300'">温控</span>
            <span v-if="fan.model === '1'">{{ fan.enableTemp }}°C</span>
            <span>/</span>
            <span :class="fan.model !== '0' ? 'text-black':'text-gray-300'">手动</span>
          </div>
        </el-card>
      </el-col>
      <!--      <el-col :span="6">-->
      <!--        <el-card class="my-2">-->
      <!--          <i v-if="rtu.surplus < 10" class="fa fa-battery-empty" aria-hidden="true" />-->
      <!--          <i v-else-if="rtu.surplus < 30" class="fa fa-battery-quarter" aria-hidden="true" />-->
      <!--          <i v-else-if="rtu.surplus < 50" class="fa fa-battery-half" aria-hidden="true" />-->
      <!--          <i v-else-if="rtu.surplus < 70" class="fa fa-battery-three-quarters" aria-hidden="true" />-->
      <!--          <i v-else class="fa fa-battery-full" aria-hidden="true" />-->
      <!--          <span style="float: right">{{ rtu.surplus }}%</span>-->
      <!--          <div class="mt-5">{{ $t('surplus') }}</div>-->
      <!--        </el-card>-->
      <!--      </el-col>-->
    </el-row>

    <el-dialog
      :visible.sync="fanSetVisible"
    >
      <el-form label-width="80px">
        <el-form-item :label="$t('model')">
          <el-radio v-model="fan.model" label="1" @change="fanModelChange">温控模式</el-radio>
          <el-radio v-model="fan.model" label="0" @change="fanModelChange">手动模式</el-radio>
        </el-form-item>
        <el-form-item v-if="fan.model === '1'" label="温度">
          <div class="flex justify-between">
            <el-input v-model="fan.enableTemp"/>
            <el-button type="primary" @click="fanTempChange">{{ $t('confirm') }}</el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog
      :visible.sync="showExplainInfo"
      append-to-body
      destroy-on-close
      width="1300px"
      top="15px"
    >
      <device-explain-info v-if="showExplainInfo" :explain="explain"/>
    </el-dialog>

  </div>
</template>

<script>
import DeviceExplainInfo from '@/components/DeviceExplainInfo'
import { formatDate, successNotice } from '@/util/common'
import { listSensorWith } from '@/api/iot/iotDeviceSensorApi'
import { sendDeviceSetting } from '@/api/iot/iotDeviceSettingApi'
import { getDeviceDetails } from '@/api/iot/iotDeviceApi'
import { leaveWebSocket, listenWebSocket } from '@/util/websocketTool'

export default {
  name: 'TsRtuBox',
  components: {
    DeviceExplainInfo
  },
  props: {
    device: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      showExplainInfo: false,
      explain: {},
      lastDeviceCore: null,
      rtu: {
        surplus: 0
      },
      fan: {
        model: '0',
        enableTemp: 0
      },
      eFlooding: null, // 水浸状态
      eHum: null, // 空气湿度
      eTemp: null, // 空气温度,
      powerList: [],
      input1: [],
      input2: [],
      input3: [],
      input4: [],
      leakageSwitchList: [],
      ip: null,
      lightningStrikes: 0,
      fanSetVisible: false,
      wsMonitor: {
        room: 'iot:device:' + this.device.deviceCore,
        onmessage: this.onSocketMsg
      }
    }
  },
  watch: {
    device: {
      deep: true,
      handler(value) {
        if (value != null) {
          this.init()
          if (this.lastDeviceCore != null) {
            leaveWebSocket(this.wsMonitor)
          }
          this.wsMonitor.room = 'iot:device:' + this.device.deviceCore
          listenWebSocket(this.wsMonitor)
          this.lastDeviceCore = this.device.deviceCore
        }
      }
    }
  }, created() {
    this.init()
    // this.initSocket()
    this.wsMonitor.room = 'iot:device:' + this.device.deviceCore
    listenWebSocket(this.wsMonitor)
  },
  beforeDestroy() {
    this.closeSocket()
  },
  methods: {
    closeSocket() {
      leaveWebSocket(this.wsMonitor)
    },
    explainClick(explain) {
      this.explain = explain
      this.showExplainInfo = true
    },
    switch1ModelChange(e) {
      sendDeviceSetting({
        deviceCore: this.device.deviceCore,
        keyName: 'setSwitch1Mode',
        value: e,
        port: '0'
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listSensorWith()
      })
    },
    fanTempChange() {
      sendDeviceSetting({
        deviceCore: this.device.deviceCore,
        keyName: 'setFan1Temp',
        value: this.fan.enableTemp,
        port: '0'
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listSensorWith()
      })
    },
    fanModelChange(e) {
      sendDeviceSetting({
        deviceCore: this.device.deviceCore,
        keyName: 'setFan1Mode',
        value: e,
        port: '0'
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listSensorWith()
      })
    },
    init() {
      this.listSensorWith()
      this.getDeviceDetails()
      if (this.device.deviceCore != null) {
        this.lastDeviceCore = this.device.deviceCore
      }
    },
    getDeviceDetails() {
      getDeviceDetails({
        deviceCore: this.device.deviceCore
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          this.ip = data.clientIp
        }
      })
    },
    onSocketMsg(nowData) {
      if (nowData.type === 'deviceData') {
        const data = JSON.parse(nowData.msg)
        // console.log(data)
        if (data.deviceUpload) {
          this.listSensorWith()
        }
      }
    },
    leakageSwitchChange(setting, value) {
      setting.value = value
      sendDeviceSetting({
        deviceCore: this.device.deviceCore,
        keyName: setting.keyName,
        value: setting.value,
        port: setting.port
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listSensorWith()
      })
    },
    powerSwitch(power) {
      sendDeviceSetting({
        deviceCore: this.device.deviceCore,
        keyName: 'setSwitch' + power.index,
        value: power.enable,
        port: '0:' + power.index
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listSensorWith()
      })
    },
    fanSwitch() {
      sendDeviceSetting({
        deviceCore: this.device.deviceCore,
        keyName: 'setFan1',
        value: this.fan.enable,
        port: '0'
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listSensorWith()
      })
    },
    reboot() {
      sendDeviceSetting({
        deviceCore: this.device.deviceCore,
        keyName: 'setReboot',
        port: '0'
      }).then(res => {
        const { code } = res
        if (code === '200') {
          successNotice(this)
        }
        this.listSensorWith()
      })
    },
    formatDate(date) {
      return formatDate(this, date)
    },
    listSensorWith() {
      listSensorWith({
        deviceCore: this.device.deviceCore,
        withExplain: true,
        withSetting: true
      }).then(res => {
        const { code, data } = res
        if (code === '200') {
          const power1 = {
            index: 1
          }
          const power2 = {
            index: 2
          }
          const power3 = {
            index: 3
          }
          const leakageSwitchList = []
          data.forEach(sensor => {
            let port
            if (sensor.port.indexOf('1') === 0) {
              port = '1'
            } else if (sensor.port.indexOf('2') === 0) {
              port = '2'
            } else if (sensor.port.indexOf('3') === 0) {
              port = '3'
            }
            if (port) {
              let leakageSwitch
              leakageSwitchList.forEach(item => {
                if (item.port === port) {
                  leakageSwitch = item
                }
              })
              if (!leakageSwitch) {
                leakageSwitch = {
                  port: 0,
                  settingList: [],
                  explainList: []
                }
                leakageSwitchList.push(leakageSwitch)
              }
              leakageSwitch.port = port
              leakageSwitch.settingList = leakageSwitch.settingList.concat(sensor.settingList)
              leakageSwitch.explainList = leakageSwitch.explainList.concat(sensor.explainList)
            }

            sensor.settingList.forEach(setting => {
              if (setting.port === '0') {
                switch (setting.keyName) {
                  case 'setFan1':
                    this.fan.enable = setting.value
                    break
                  case 'setFan1Mode':
                    this.fan.model = setting.value
                    break
                  case 'setFan1Temp':
                    this.fan.enableTemp = setting.value
                    break
                  case 'setSwitch1':
                    power1.enable = setting.value
                    break
                  case 'setSwitch1Mode':
                    power1.mode = setting.value
                    break
                  case 'setSwitch1Freq':
                    power1.freq = setting.value
                    break
                  case 'setSwitch1Time':
                    power1.time = setting.value
                    break
                  case 'setSwitch2':
                    power2.enable = setting.value
                    break
                  case 'setSwitch2Mode':
                    power2.mode = setting.value
                    break
                  case 'setSwitch2Freq':
                    power2.freq = setting.value
                    break
                  case 'setSwitch2Time':
                    power2.time = setting.value
                    break
                  case 'setSwitch3':
                    power3.enable = setting.value
                    break
                  case 'setSwitch3Mode':
                    power3.mode = setting.value
                    break
                  case 'setSwitch3Freq':
                    power3.freq = setting.value
                    break
                  case 'setSwitch3Time':
                    power3.time = setting.value
                    break
                }
              }
            })
            sensor.explainList.forEach(explain => {
              if (explain.port === '0') {
                switch (explain.keyName) {
                  case 'V_bat':
                    this.rtu.v = explain.value
                    break
                  case 'I_charge':
                    this.rtu.i = explain.value
                    break
                  case 'T_ntc':
                    this.rtu.temp = explain.value
                    this.eTemp = explain
                    break
                  case 'Surplus':
                    this.rtu.surplus = parseInt(explain.value)
                    break
                  // case 'Fan1_Mode':
                  //   this.fan.model = explain.value
                  //   break
                  case 'I_12VDC1':
                    power1.i = explain.value
                    break
                  case 'I_12VDC2':
                    power2.i = explain.value
                    break
                  case 'I_12VDC3':
                    power3.i = explain.value
                    break
                  case 'Input_Status1':
                    this.input1 = explain
                    break
                  case 'Input_Status2':
                    this.input2 = explain
                    break
                  case 'Input_Status3':
                    if (explain.remark === '') {
                      explain.remark = '输入检测3'
                    }
                    this.input3 = explain
                    break
                  case 'Input_Status4':
                    if (explain.remark === '') {
                      explain.remark = '输入检测4'
                    }
                    this.input4 = explain
                    break
                  case 'AC_InputV':
                    this.rtu.acV = explain
                    break
                  case 'AC_InputI':
                    this.rtu.acI = explain
                    break
                }
              }

              switch (explain.keyName) {
                case 'lightningStrikes':
                  this.lightningStrikes = explain.value
                  break
              }

              if (explain.value !== '') {
                switch (explain.keyName) {
                  case 'eHum':
                    if (!explain.hidden) {
                      this.eHum = explain
                    }
                    break
                  case 'eTemp':
                    if (!explain.hidden) {
                      this.eTemp = explain
                    }
                    break
                  case 'eFlooding':
                    if (!explain.hidden) {
                      this.eFlooding = explain
                    }
                    break
                }
              }
            })
          })

          this.leakageSwitchList = leakageSwitchList
          this.powerList = [power1, power2, power3]
        }
      })
    }
  }
}
</script>

